<template lang="pug">
div
  FixedScroll
    div(slot="fixed")
      PageHeader(pageTitle="供应商退货")
        div(
            v-if="$root.User.permMap['Done(退货业务)']"
            slot="right"
            :class="{'save-disabled': !saveEnabled, active: saveEnabled}"
            @click="save"
            ) 完成

      ScanSearch(
          placeholder="退货单"
          :initSearchValue="searchValue"
          @search="search"
          @scan="search"
          )

      g-v.info(v-if="info")
        KvPair(v-if="info.ReturnNo" k="单号" :v="info.ReturnNo")
        KvPair(v-if="info.StorgelocationCode" k="实体仓库" :v="info.StorgelocationCode")
        KvPair(v-if="info.WmNo" k="逻辑仓库" :v="info.WmNo")

    InputTable.table(
        slot="scroll"
        :headList="headList"
        :body="body"
        :isLoading="isLoading"
        :disabled="!saveEnabled"
        @check-input="checkInput"
        @click-row="clickRow"
        )

</template>

<script>
import api from "$api"
import util from "$util"
import { mapState, mapGetters } from "vuex"

export default {
  data() {
    return {
      searchValue: "",
      isLoading: false,
      saveEnabled: false,
      hasIllegalInput: false, // 是否包含不合法的输入

      clickableRow: {}, // 可点击的行

      loading: {
        search: false,
        save: false,
      },

      headList: [
        { field: "PartNo", title: "物料号", checked: true },
        { field: "PartCname", title: "物料名称", checked: true },
        { field: "SupplierNum", title: "厂家号", checked: true },
        { field: "RequiredInboundPackageQty", title: "需退货数", checked: true },
        { field: "PackSize", title: "实退数", checked: true },
        { field: "PartType", title: "物料类型", checked: true },
        { field: "BatchNo", title: "批次", checked: true },
      ],
    }
  },
  computed: {
    ...mapState({
      info: state => state.refund.info,
      body: state => state.refund.body,
      partnoAndList: state => state.refund.partnoAndList,
      active: state => state.refund.active,
    }),
  },
  watch: {
    active(v) {
      // 切换tab时要重新绑定手机上的扫描键
      if (v === "ScanPage") {
        this.registerScanner()
        this.$forceUpdate()
      }
    },
  },
  methods: {
    async search(value) {
      if (this.loading.search) {
        return
      }
      if (value === "") {
        return
      }
      // 重置所有状态
      this.$store.commit("refund/reset")

      this.loading.search = true
      try {
        let data = await api.RefundSearch({
          ReturnNo: value,
        })
        this.reset()
        this.$store.commit("refund/setInfo", {
          info: data.ReturnInfo,
        })

        // 检查状态
        let inputRowList = [] // 可以输入的行
        let i = 0
        for (let item of data.ReturnDetailInfo) {
          if (item.IsBatch === 0) {
            util.Alert(`物料[${item.PartNo}]的管理模式未维护,请维护库位与物料关系后操作`)
            return
          }
          if (item.IsBatch === 1) {
            inputRowList.push(i)
          } else {
            this.clickableRow[i] = true // 可以点击的行
          }
          i++
        }
        switch (data.ReturnInfo.ConfirmFlag) {
          case 0:
            util.Alert("单据未确认，不能在移动端操作")
            return
          case 2:
            util.Toast("已完成")
            break
          default:
            this.saveEnabled = true
            break
        }

        // 根据规则给退货数设置默认值
        if (data.ReturnInfo.ConfirmFlag === 1 && inputRowList.length < i) {
          for (let item of data.ReturnDetailInfo) {
            item.PackSize = 0
          }
          for (let index of inputRowList) {
            data.ReturnDetailInfo[index].PackSize = data.ReturnDetailInfo[index].RequiredInboundPackageQty
          }
        } else {
          for (let item of data.ReturnDetailInfo) {
            item.PackSize = item.RequiredInboundPackageQty
          }
        }

        // 给可点击的行设置样式
        let styleMap = new Array(data.ReturnDetailInfo.length)
        let firstField = this.headList[0].field
        for (let k in this.clickableRow) {
          styleMap[k] = {
            [firstField]: {
              color: "#1E88E5",
            }
          }
        }

        this.$store.commit("refund/setBody", {
          body: {
            inputRowList,
            styleMap,
            enumColumnMap: {
              PartType: api.Enum.Refund.PartType,
            },
            list: data.ReturnDetailInfo,
          },
        })
      } catch(err) {
        this.$root.error(err)
      } finally {
        this.isLoading = false
        this.loading.search = false
      }
    },

    async save() {
      if (this.loading.save) {
        return
      }
      if (!this.info || !this.saveEnabled) {
        return
      }
      if (this.hasIllegalInput) {
        util.Alert("输入框中包含不合法的数据")
        return
      }

      for (let item of this.body.list) {
        if (item.RequiredInboundPackageQty !== parseInt(item.PackSize)) {
          util.Alert(`物料${item.PartNo}的数量与实际数量不等`)
          return
        }
      }

      let operType = "Batch"
      if (Object.keys(this.clickableRow).length > 0) {
        operType = "Return"
      }
      
      // 筛选出合格的电池
      let barcodeDetailList = []
      for (let k in this.partnoAndList) {
        let list = this.partnoAndList[k].barcodeList
        let statusMap = this.partnoAndList[k].statusMap
        for (let item of list) {
          if (statusMap[item.BarcodeData] === util.STATUS_OK) {
            item.TranNo = this.info.RefundNo
            barcodeDetailList.push(item)
          }
        }
      }

      this.loading.save = true
      try {
        await api.RefundSave({
          ReturnId: this.info.ReturnId,
          OperType: operType,
          barcodeDetailList,
        })
        this.reset()

        // 清除电池缓存数据
        this.$store.commit("refund/clearBatteryCache")
        this.info.ConfirmFlag = 2
        this.$store.commit("refund/setInfo", {
          info: this.info,
        })
        util.Toast("完成成功")
      } catch(err) {
        this.$root.error(err)
      } finally {
        this.isLoading = false
        this.loading.save = false
      }
    },

    // 重置本页的状态
    reset() {
      this.saveEnabled = false
    },

    // 检查输入数据
    checkInput(v) {
      if (v == null || v === "") {
        return
      }
      let isNatural = /^(0|[1-9]\d*)$/.test(v)
      if (!isNatural) {
        this.hasIllegalInput = true
        util.Toast(`错误的输入: ${v}`)
      } else if (this.hasIllegalInput) {
        this.hasIllegalInput = false
      }
    },

    // 点击行转到扫电池页面
    clickRow(row, index) {
      if (this.clickableRow[index]) {
        this.$store.commit("refund/switchToBarcode", {
          index,
        })
      }
    },

    registerScanner() {
      util.registerScanner((data) => {
        this.searchValue = data
        this.search(data)
      })
    },
  },

  created() {
    this.registerScanner()
  },
}
</script>

<style lang="stylus" scoped>

.save-disabled
  color: grey500

.active:active
  active-color()

.info
  border: 1px solid grey200

.table
  scan-table()

</style>
